<script>
import { mapState } from "vuex";
import { env } from "./config";
export default {
  onLaunch: function () {
    console.log("App Launch");
    wx.cloud.init({
      env, // 自行配置自己的云开发环境
    });
    this.getUserInfoFromDB();
  },
  computed: { ...mapState(["userInfo", "userList"]) },
  methods: {
    // 判断用户信息是否存在（不存在则直接创建新用户）
    async getUserInfoFromDB() {
      try {
        const userId = await this.getUserOpenId();
        await this.$store.dispatch("getUserInfo", { type: 4, userId });
        if (!this.userInfo) {
          const user = await this.addUser();
          user._openid = userId;
          this.$store.commit("setUserInfo", user); // 能到添加新用户的信息存储
        }
      } catch (err) {
        console.log("获取失败：", err);
      }
    },

    // 借助云函数获取用户openid
    getUserOpenId() {
      return new Promise((resolve, reject) => {
        wx.cloud.callFunction({
          name: "getId",
          success: (res) => {
            resolve(res.result.openid);
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    // 数据库中添加用户信息
    async addUser() {
      const db = wx.cloud.database();
      const user = this.initUser();
      try {
        await this.initTaskList(user); // 初始化分配的任务列表
        await db.collection("user").add({ data: user });
      } catch (err) {
        console.log("添加用户错误：", err);
      }
      return user;
    },

    // 初始化用户信息
    initUser() {
      const user = {};
      user.area = "";
      user.avatar = "";
      user.nickName = "";
      user.introduce = "这个人很神秘,没有填写介绍。";
      user.grade = "";
      user.qq = "";
      user.school = "";
      user.wx = "";
      user.cls = "";
      user.allocTask = "";
      user.liked = 0;
      user.collection = [];
      user.discussion = [];
      user.fans = [];
      user.focusList = [];
      user.taskList = [];
      user.teamTaskList = [];
      user.myTeam = [];
      user.tags = [];
      user.joinTeam = [];
      user.createTime = new Date();
      this.$store.commit("setUserInfo", user);
      return user;
    },

    // 初始化创建任务列表(分配给我的)
    async initTaskList(user) {
      const item = {};
      item.isMe = true;
      item.isTeam = false;
      item.title = "分配给我的";
      item.tasks = [];
      item.createTime = new Date();
      try {
        const res = await wx.cloud.database().collection("taskList").add({
          data: item,
        });
        user.allocTask = res._id;
        console.log("初始化任务列表成功:", res);
      } catch (err) {
        console.log("初始化任务列表失败：", err);
      }
    },
  },
};
</script>

<style lang="scss">
@import "/animate/animate.min.css";
@import "/wxcomponents/vant/common/index.wxss";
page {
  height: 100%;
  background: #eee;
}
</style>
